package com.stanwind.netty.api;

import com.stanwind.netty.domain.pojo.Player;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by StanWind on 2017/2/17.
 */
@Component
public class ClientUtils {
    private Map<String, Player> playerMap;

    @PostConstruct
    public void init() {
        playerMap = new HashMap<String, Player>();
    }

    /**
     * 向map增加player
     *
     * @param player
     * @return 如果存在就返回map中更新的player
     */
    public Player add(Player player) {
        Iterator<Map.Entry<String, Player>> iterator = playerMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Player> entry = iterator.next();
            //已经在列表内 更新channel信息
            if (player.getCharacter().getAccountId().equals(entry.getKey())) {
                entry.getValue().setChannel(player.getChannel());
                return entry.getValue();
            }
        }

        playerMap.put(player.getCharacter().getAccountId(), player);
        return player;
    }

    public void del(String accountId) {
        playerMap.remove(accountId);
    }

    public void del(Player player) {
        playerMap.remove(player.getCharacter().getAccountId());
    }


    /**
     * 拿到玩家
     *
     * @param ctx channelHandlerContext
     * @return 玩家对象 可能为null
     */
    public Player getPlayer(ChannelHandlerContext ctx) {
        return getPlayer(ctx.getChannel().getId());
    }


    /**
     * 通过channelId遍历查找player
     *
     * @param channelID
     * @return 可能为null
     */
    public Player getPlayer(int channelID) {
        Player player = null;
        synchronized (playerMap) {
            Iterator<Map.Entry<String, Player>> iterator = playerMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Player> entry = iterator.next();
                //已经在列表内 更新channel信息
                Channel channel = entry.getValue().getChannel();
                if (channel == null)
                    return null;
                if (channel.getId().equals(channelID)) {
                    player = entry.getValue();
                    break;
                }
            }
        }
        return player;
    }
}
